#!/sbin/openrc-run

name="${RC_SVCNAME}"
command="/usr/sbin/bird"

: ${supervisor:="supervise-daemon"}
: ${CONF_FILE:="/etc/${RC_SVCNAME}.conf"}
: ${SOCK_PATH:="/run/${RC_SVCNAME}.ctl"}
: ${USER:="bird"}
: ${GROUP:="bird"}

command_args="-u ${USER} -g ${GROUP} -s ${SOCK_PATH} -c ${CONF_FILE} ${BIRD_ARGS}"
command_args_foreground="-f"
command_background=true

extra_commands="configtest"
extra_started_commands="reload"

depend() {
	need net
	use logger
	after firewall
}

start_pre() {
	# Ensure permissions on configuration file are correct for upgrades.
	checkpath --file --owner root:${GROUP} --mode 0640 "${CONF_FILE}"
	# Validate the config file before starting
	/usr/sbin/bird -p -c "${CONF_FILE}"
}

configtest() {
	/usr/sbin/bird -p -c "${CONF_FILE}" 1>/dev/null 2>&1
	ret=$?
	if [ $ret -ne 0 ]; then
		eerror "${RC_SVCNAME} has detected an error in your setup:"
		/usr/sbin/bird -p -c "${CONF_FILE}"
	fi
	return $ret
}

reload() {
	ebegin "Reloading ${RC_SVCNAME} configuration"
	/usr/sbin/birdc -s "${SOCK_PATH}" "configure check" 1>/dev/null 2>&1
	ret=$?
	if [ $ret -eq 0 ]; then
		/usr/sbin/birdc -s "${SOCK_PATH}" "configure"
	else
		eerror "${RC_SVCNAME} has detected an error in your setup:"
		/usr/sbin/birdc -s "${SOCK_PATH}" "configure check"
	fi
	eend $?
}
